package com.ruiyangwang.ListenBook.repository;

import com.ruiyangwang.ListenBook.dataObject.AlbumDO;
import com.ruiyangwang.ListenBook.util.DButil;
import com.ruiyangwang.ListenBook.util.Log;
import com.ruiyangwang.ListenBook.viewObject.UserV0;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author syzygy
 * @date 2022/07/20 21:44
 **/

public class AlbumRepo {
    @SneakyThrows
    public  void insertAlbums(UserV0 userVO, String title, String cover,int state) {
        String sql = "insert into albums (uid,title,cover,state) values (?,?,?,?);";
        try(Connection c = DButil.connection()){
            try(PreparedStatement ps = c.prepareStatement(sql)){
                ps.setInt(1,userVO.uid);
                ps.setString(2,title);
                ps.setString(3,cover);
                ps.setInt(4,state);
                Log.println("所执行的sql为" + ps);
                ps.executeUpdate();
            }
        }
    }

@SneakyThrows
    public AlbumDO selectOneByUidAndAid(UserV0 currentUser, int aid) {
        String sql = "select aid, uid, title, cover, state from albums where  uid = ? and aid = ?";
        try(Connection c = DButil.connection()){
            try(PreparedStatement ps = c.prepareStatement(sql)){
                ps.setInt(1,currentUser.uid);
                ps.setInt(2,aid);
                Log.println("执行sql" + ps);
                try(ResultSet rs = ps.executeQuery()){
                    if(!rs.next()){
                        return null;
                    }
                    return new AlbumDO(rs.getInt("aid"),rs.getInt("uid"),rs.getString("title"),rs.getString("cover"),rs.getInt("state"));

                }
            }
        }
    }
    @SneakyThrows
    public AlbumDO selectOneByAid(int aid) {
        String sql = "select aid, uid, title, cover, state from albums where aid = ?";
        try(Connection c = DButil.connection()){
            try(PreparedStatement ps = c.prepareStatement(sql)){
                ps.setInt(1,aid);
                Log.println("执行sql" + ps);
                try(ResultSet rs = ps.executeQuery()){
                    if(!rs.next()){
                        return null;
                    }
                    return new AlbumDO(rs.getInt("aid"),rs.getInt("uid"),rs.getString("title"),rs.getString("cover"),rs.getInt("state"));

                }
            }
        }
    }
@SneakyThrows
    public void deleteByAidAndTid(int aid, int tid) {
        String sql = "delete from relations where aid = ? and tid = ?";
        try(Connection c = DButil.connection()){
            try(PreparedStatement ps = c.prepareStatement(sql)){
                ps.setInt(1,aid);
                ps.setInt(2,tid);
                Log.println("所执行的sql为" + ps);
                ps.executeUpdate();
            }
        }
    }
}